import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/pages/Login'
import LoginForm from '@/components/LoginForm'
import FirstLoginForm from '@/components/FirstLoginForm'
import Index from '@/pages/Index'
import ForgetPassword from '@/pages/ForgetPassword'
import Setting from '@/pages/Setting'
import HolidaySet from '@/components/HolidaySet'
import TimeSet from '@/components/TimeSet'
import ChangePassword from '@/components/ChangePassword'
import { MessageBox } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

Vue.use(Router)

// 配置NProgress进度条选项  —— 动画效果
NProgress.configure({ease: 'ease', speed: 500})

// 路由
const router = new Router({
    mode: 'history',
    routes: [
        {
            path: '/index',
            meta: {isLogin: true},
            component: Index
        },
        {
            path: '/login',
            component: Login,
            children: [
                {
                    path: '',
                    component: LoginForm
                },
                {
                    path: 'firstlogin',
                    component: FirstLoginForm
                }
            ]
        },
        {
            path: '/forgetpassword',
            component: ForgetPassword
        },
        {
            path: '/setting',
            meta: {isLogin: true},
            component: Setting,
            children: [
                {
                    path: '',
                    redirect: 'holidayset'
                },
                {
                    path: 'holidayset',
                    meta: {isLogin: true},
                    component: HolidaySet
                },
                {
                    path: 'timeset',
                    meta: {isLogin: true},
                    component: TimeSet
                },
                {
                    path: 'changepassword',
                    meta: {isLogin: true},
                    component: ChangePassword
                }
            ]
        },
        {
            path: '/*',
            meta: {isLogin: true},
            redirect: '/Index'
        }
    ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
    NProgress.start()
    
    if (to.meta.isLogin) {
        if (localStorage.token) {
            // 离开时段设置页面判断是否保存
            if (from.path.toLowerCase() == '/setting/timeset' && sessionStorage.isEdit) {
                MessageBox.confirm('You have made changes not saved whether to leave?', 'Tips').then(() => {
                    next()
                }).catch(() => {})
            } else {
                next()
            }
        } else {
            next('/login')
        }
    } else {
        next()
    }
})

router.afterEach(transition => {
    NProgress.done()
})

export default router